package leetcode.top100;

import org.junit.Test;

import java.util.Arrays;

/**
 * @author ：zsy
 * @date ：Created 2022/12/16 7:57 PM
 * @description：
 */
public class _34_在排序数组中查找元素的第一个和最后一个位置 {
    @Test
    public void test() {
        System.out.println(Arrays.toString(new Solution().searchRange(new int[]{5, 7, 7, 8, 8, 10}, 7)));
    }

    class Solution {
        public int[] searchRange(int[] nums, int target) {
            int n = nums.length;
            int[] ans = new int[]{-1, -1};
            if (n == 0) {
                return ans;
            }
            int l = 0;
            int r = n - 1;
            // 拿到大于等于target的最小值
            while (l < r) {
                int mid = l + r >> 1;
                if (nums[mid] >= target) {
                    r = mid;
                } else {
                    l = mid + 1;
                }
            }
            if (nums[l] != target) {
                return ans;
            }
            ans[0] = l;
            r = n - 1;
            // 拿到小于等于target的最大值
            while (l < r) {
                int mid = l + r + 1 >> 1;
                if (nums[mid] <= target) {
                    l = mid;
                } else {
                    r = mid - 1;
                }
            }
            ans[1] = l;
            return ans;
        }
    }
}
